package com.innovation.chengzhangriji.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.AllBabyResponse;
import com.innovation.chengzhangriji.http.BabyQRCodeResponse;
import com.innovation.chengzhangriji.http.BabyResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteBabyAvatarView;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.JoinNewAdapter;
import com.innovation.chengzhangriji.util.FileUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orhanobut.logger.Logger;

import java.io.File;

public class JoinNewActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener, View.OnClickListener {

    private static final String[] list = new String[]{"爸爸", "妈妈", "爷爷", "奶奶", "姥爷", "姥姥"};

    private String mSearchPhone,QRCodeName;

    private JoinNewAdapter mJoinNewAdapter;

    private RecyclerView mRecyclerView;

    private CuteButton mButtonJoin;

    private CuteTextView mInputName,tv_phone,tv_nophone,baby_photo_text;
    private RelativeLayout relativeLayout_join_new,relativeLayout_hasphone,relativeLayout_bohasphone,layout_noloading;

    private ListPopupWindow lpw;

    private ImageView mImageEmpty;
    private int length=-1,babyId_saoyisao=-1;
    private CuteBabyAvatarView babyAvatarView;
    private LinearLayout linearLayout;
    private ProgressDialog progressDialog;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String imageUrl = null;
            switch (requestCode) {
                case 4:
                    mInputName.setText(data.getStringExtra("relationship"));
                    break;
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSearchPhone = getIntent().getStringExtra("searchPhone");
        QRCodeName = getIntent().getStringExtra("QRCodeName");
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在加载...");
        progressDialog.show();
        setupLayout();
        Log.e("mSearchPhone", "" + mSearchPhone);
        Log.e("QRCodeName", "" + QRCodeName);
        if (!"".equals(mSearchPhone) && mSearchPhone != null){
            requestSearchAllBaby();
        } else if (!("").equals(QRCodeName) && QRCodeName != null){
            getBabyIDByQRCode(QRCodeName);
        }
    }

    @Override
    public void onClickLeft() {
//        Intent intent = new Intent(this, SelectActivity.class);
//        startActivity(intent);
//        finish();
        onBackPressed();
    }

    @Override
    public void onClickRight() {

    }

//    @Override
//    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        String item = list[position];
//        mInputName.setText(item);
//        lpw.dismiss();
//    }

    @Override
    public void onClick(final View v) {
        if (v.getId() == R.id.button_join_new) {
            if (length>0) {
                LoginInfo loginInfo = Config.getLoginInfo(this);
                if (loginInfo == null) {
                    return;
                }
                String phone = loginInfo.getPhone();
                String token = loginInfo.getToken().getAccessToken();
                int babyID=0;
//                if (babyId_fromSYS != 0 ){
//                    babyID = babyId_fromSYS;
//                }else {
                if (!("").equals(QRCodeName) && QRCodeName != null){
                    babyID = babyId_saoyisao;
                }else{
                     babyID = mJoinNewAdapter.getJoinBabyID();
                }
                String role = mInputName.getText().toString();
                if (TextUtils.isEmpty(role)) {
                    tipShow("请输入称谓");
                    return;
                }
                Log.e("QRCodeNamebbb",""+babyID);
                Client.requestJoin(this, phone, token, babyID, role, new ResponseHandler() {

                    @Override
                    public void onStart() {
//                        showProgressDialog(null, null);
                    }

                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        if (value.getAsInt() == 1) {
                            tipShow("申请成功！坐待对方验证吧！");
                            Intent intent = new Intent(JoinNewActivity.this, HomeActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                        } else {
                            tipShow("未知的错误");
                        }
                    }

                    @Override
                    public void onChZhRJFailure(String value) {
                        tipShow(value);
                    }

                    @Override
                    public void onInnovationFinish() {
                        dismissProgressDialog();
                    }

                    @Override
                    public void onInnovationExceptionFinish() {
                        dismissProgressDialog();
                    }
                }, networkUnavailableSampleImpl());
            }
        }
    }

//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
//        final int DRAWABLE_RIGHT = 2;
//        if (event.getAction() == MotionEvent.ACTION_UP) {
//            if (event.getRawX() >= (mInputName.getRight() - mInputName.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
//                lpw.show();
//                return true;
//            }
//        }
//        return false;
//    }

    private void setupLayout() {
        setContentView(R.layout.activity_join_new);
//        showProgressDialog(null, "正在加载...");
        layout_noloading = (RelativeLayout) findViewById(R.id.layout_noloading);
        CuteToolbar cuteToolbar = (CuteToolbar) findViewById(R.id.join_new_toobar);
        cuteToolbar.setOnClickCuteToolbarListener(this);
        babyAvatarView = (CuteBabyAvatarView) findViewById(R.id.baby_photo_join_new);
        linearLayout = (LinearLayout) findViewById(R.id.saoyisao_layout);
        baby_photo_text = (CuteTextView) findViewById(R.id.baby_photo_text);
        tv_phone = (CuteTextView) findViewById(R.id.text_phone);
        tv_nophone = (CuteTextView) findViewById(R.id.text_hasnophone);
        relativeLayout_hasphone = (RelativeLayout) findViewById(R.id.relativeLayout_join_new_head);
        relativeLayout_bohasphone = (RelativeLayout) findViewById(R.id.relativeLayout_nohasnumber);
        if (!TextUtils.isEmpty(QRCodeName)){
            tv_phone.setVisibility(View.INVISIBLE);
        }else {
            tv_phone.setVisibility(View.VISIBLE);
            tv_phone.setText("手机号: " + mSearchPhone);
        }
        relativeLayout_join_new = (RelativeLayout) findViewById(R.id.relativeLayout_join_new_gonext);
        relativeLayout_join_new.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent  = new Intent(JoinNewActivity.this,PetnameListActivity.class);
                intent.putExtra("type","relationship");
                intent.putExtra("relationship",mInputName.getText().toString());
                startActivityForResult(intent,4);
            }
        });
        mInputName = (CuteTextView) findViewById(R.id.tv_join_new_name);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mJoinNewAdapter = new JoinNewAdapter();
        mRecyclerView.setAdapter(mJoinNewAdapter);
        mButtonJoin = (CuteButton) findViewById(R.id.button_join_new);

//        mInputName = (CuteEditText) findViewById(R.id.text_input_name);
//        mImageEmpty = (ImageView) findViewById(R.id.image_empty);

//        lpw = new ListPopupWindow(this);
//        lpw.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
//        lpw.setAnchorView(mInputName);
//        lpw.setModal(true);
//        lpw.setOnItemClickListener(this);
//        mInputName.setOnTouchListener(this);
        mButtonJoin.setOnClickListener(this);

    }
    // 根据二维码获得宝贝信息
    private void getBabyIDByQRCode(String qrcode) {
        Log.e("QRCodeName","getBabyIDByQRCode");
        LoginInfo login = Config.getLoginInfo(JoinNewActivity.this);
        if (login == null) {
            return;
        }
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
//        String member = mInputName.getText().toString();
        String member = "";
        Client.requestBabyQRCode(JoinNewActivity.this, phone, token, member, qrcode, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
//                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                BabyQRCodeResponse response = get(value.toString(), BabyQRCodeResponse.class);
                Log.e("QRCodeName","onInnovationSuccess111");
                if (response != null) {
//                    requestJoin(response.getId());
//                    Intent intent = new Intent(JoinNewActivity.this,JoinNewActivity.class);
//                    intent.putExtra("babyId",response.getId());
//                    startActivity(intent);
                    length = 1;
                    requestBaby(response.getId());

                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }
        }, networkUnavailableSampleImpl());
    }
    private void requestSearchAllBaby() {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        Client.requestSearchAllBaby(this, phone, token, mSearchPhone, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
//                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                AllBabyResponse response = get(value.toString(), AllBabyResponse.class);
                length = response.getData().length;
                if (response == null || response.getData().length == 0) {
//                    mImageEmpty.setVisibility(View.VISIBLE);
                    relativeLayout_bohasphone.setVisibility(View.VISIBLE);
                    relativeLayout_bohasphone.setBackgroundResource(R.mipmap.nulldate);
                    relativeLayout_hasphone.setVisibility(View.INVISIBLE);
                    tv_nophone.setText("手机号: " + mSearchPhone);

                } else {
//                    layout_noloading.setVisibility(View.VISIBLE);
                    relativeLayout_hasphone.setVisibility(View.VISIBLE);
                    relativeLayout_bohasphone.setVisibility(View.INVISIBLE);
                    mRecyclerView.setVisibility(View.VISIBLE);
//                    mButtonJoin.setVisibility(View.VISIBLE);
                    BabyResponse[] babyResponses = response.getData();
                    mJoinNewAdapter.setBabyResponses(babyResponses);
                    mJoinNewAdapter.notifyDataSetChanged();
                    tv_phone.setText("手机号: " + mSearchPhone);
                }
                progressDialog.dismiss();
            }

            @Override
            public void onChZhRJFailure(String value) {
                relativeLayout_bohasphone.setVisibility(View.VISIBLE);
                relativeLayout_bohasphone.setBackgroundResource(R.mipmap.nulldate);
                relativeLayout_hasphone.setVisibility(View.INVISIBLE);
                tv_nophone.setText("手机号: " + mSearchPhone);
                progressDialog.dismiss();
            }

            @Override
            public void onInnovationFinish() {
                progressDialog.dismiss();
            }

            @Override
            public void onInnovationExceptionFinish() {
                progressDialog.dismiss();
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                progressDialog.dismiss();
            }
        });
    }

    private void requestBaby(int id) {
        Log.e("QRCodeName","requestBaby");
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        babyId_saoyisao = id;

        Client.requestBaby(this, phone, token, id,0, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
//                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                BabyResponse response = get(value.toString(), BabyResponse.class);
                Log.e("QRCodeName","onInnovationSuccess");
                if (response != null){
//                    length = 1;
//                    BabyResponse[] babyResponses = new BabyResponse[1];
//                    babyResponses[0]= response;
//                    relativeLayout_hasphone.setVisibility(View.VISIBLE);
//                    relativeLayout_bohasphone.setVisibility(View.INVISIBLE);
//                    mRecyclerView.setVisibility(View.VISIBLE);
//                    mJoinNewAdapter.setBabyResponses(babyResponses);
//                    mJoinNewAdapter.notifyDataSetChanged();
//                    linearLayout.setVisibility(View.VISIBLE);
                    relativeLayout_bohasphone.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.VISIBLE);
                    baby_photo_text.setText(response.getName());
                    babyAvatarView.setSex(response.getGender());
                    babyAvatarView.setAvatar(response.getImageUrl());
                }
                progressDialog.dismiss();

            }

            @Override
            public void onChZhRJFailure(String value) {
//                relativeLayout_bohasphone.setVisibility(View.VISIBLE);
//                relativeLayout_hasphone.setVisibility(View.INVISIBLE);
//                tv_nophone.setText("手机号: " + mSearchPhone);
                progressDialog.dismiss();
            }

            @Override
            public void onInnovationFinish() {
                progressDialog.dismiss();
            }

            @Override
            public void onInnovationExceptionFinish() {
                progressDialog.dismiss();
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                progressDialog.dismiss();
            }
        });
    }
}
